import React, { useEffect, useRef, useState, useContext } from 'react';
import { Graph, Node, Shape } from '@antv/x6';
import { Button, message, Select, Modal, Spin } from 'antd';
import { ChatContext, } from '@/app/chat-context';
import '@antv/x6-react-shape'
import {
  X6_PORT_OUT_NAME,
  X6_PORT_OUT_NAME1,
  X6_NODE_NAME,
  PORT_HOVER,
  PORT_SELECTED,
  PORT,
  NODE,
  NODE_HOVER,
  NODE_SELECTED,
  EDGE,
  EDGE_SELECTED,
  EDGE_HOVER,
} from './hooks/dag-config';
import Image from 'next/image';
import { DeleteOutlined } from '@ant-design/icons';
import { PlusOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import _ from 'lodash'
import { WorkbenchesContext, } from '@/components/workbenches/workbenches-context';

import EdgeModal from './edgeModal';
import useModal from './hooks/useModal';
import CustomNode from './CustomNode';
import WorkbenchesIcon from '@/components/workbenches/icons';
import { useTranslation } from 'react-i18next';
import useCanves from './hooks/useCanves';
import SaveCanvasModal from './saveCanvasModal';
import DataCard from './DataCard';
import InDetailModel from '../components/inDetail'
import { cloneDeep } from 'lodash';
import { modelDelete, } from '@/client/api/workbenches';

const NODE_HEIGHT = 220;
const NODE_HIDE_HEIGHT = 60;
const NODE_WIDTH = 450;
let hoverCell: any = null;


const FlowEditor = ({ setCopilotVisible }) => {
  const { mode } = useContext(ChatContext);
  const { t, i18n } = useTranslation();

  const {
    currentItem,
    graphValue: graph,
    treeData,
    items,
    setItems,
    activeKey,
    getCurrentItemChange,
    canvasResizeChange,
    loading,
    delTabChange,
  } = useContext(WorkbenchesContext);
  // 操作节点连线弹窗
  const {
    open,
    form,
    setForm,
    setOpen,
    modalType,
    handleCreate,
  } = useModal();
  // 画布
  const {
    container,
    removeNode,
    updateNodeData,
    updateNodeStyle,
    handleAddNode,
    handleSave,
    nodeData,
    checkNodeConnections,
    checkedState,
    handleCheckboxChange,
    toJSONChange,
    updateStatusChange,
    edgeContextMenu,
    closeEdgeContextMenu
  } = useCanves({ graph, handleCreate, setCopilotVisible, canvasResizeChange, });
  // 保存画布信息弹窗
  const {
    open: saveCanvasModalOpen,
    form: saveCanvasModalForm,
    setForm: saveCanvasModalSetForm,
    setOpen: saveCanvasModalSetOpen,
    modalType: saveCanvasModalModalType,
    updataNodeModal: saveCanvasModalUpdataNodeModal,
  } = useModal();
  const [openInDetailModel, setOpenInDetailModel] = useState(false)
  const [detailType, setDetailtype] = useState('')
  let [measurementValue, setMeasurementValue] = useState(0)
  /* detailType
    model:模型
    log:日志
    preview:预览 
  */
  //模型详情
  const openDetailsmodel = (type: string) => {
    if (!currentItem?.modelInfo?.id) return;
    setMeasurementValue(++measurementValue)
    setDetailtype(type)
    setOpenInDetailModel(true)
  }
  // AI生成按钮  打开copolot面板
  const handleAIGenerate = () => {
    setCopilotVisible(true)
  };

  const containerStyle: React.CSSProperties = {
    position: 'relative',
    height: 400,
    padding: 18,
    overflow: 'hidden',
  };
  const setDataSource = (value: string) => {
    if (graph.current && value) {
      const dataSource: any = treeData.find((i: any) => i.id == value)
      if (!dataSource?.key) return;
      const newPanes: any = _.cloneDeep(items);
      const tabIndex = newPanes.findIndex((i: any) => i.key == activeKey);
      if (tabIndex != -1) {
        newPanes[tabIndex] = {
          ...newPanes[tabIndex],
          dataSourceId: dataSource.id,
          dataSourceData: dataSource.children.find((i: any) => i.nodeType == 'Schema'),
          dataSourceQuery: dataSource.children.find((i: any) => i.nodeType == 'Query_Catalog'),
        };

        setItems(newPanes);
      }
      toJSONChange(newPanes[tabIndex]);
      graph.current.clearCells();
    }
  }
  // 监听全局点击关闭菜单
  useEffect(() => {
    if (!edgeContextMenu) return;
    const handler = () => closeEdgeContextMenu();
    window.addEventListener('click', handler);
    return () => window.removeEventListener('click', handler);
  }, [edgeContextMenu, closeEdgeContextMenu]);
  useEffect(() => {
    if (!currentItem?.modelInfo?.id) {
      setOpenInDetailModel(false);
    }
  })
  const delModel = async () => {
    Modal.confirm({
      content: '是否删除当前模型？',
      okText: '删除',
      onOk: async () => {
        const id = currentItem?.key.split('_')[1];
        modelDelete({ id }).then((res => {
          if (res.data.code == 0) {
            delTabChange({ key: currentItem.key });
            message.success(res.data.msg || `操作成功!`);
          } else {
            message.error(res.data.msg || `操作失败!`);
          }
        }));
      },
      onCancel() { },
    });
  };
  return (
    <div className='w-full h-full relative' style={containerStyle}>
      <DataCard currentItem={currentItem} nodeData={nodeData} checkedState={checkedState} handleCheckboxChange={handleCheckboxChange} />

      <div className='flex items-center workbenches-B620E0'>
        <Button onClick={() => {
          if (!currentItem?.dataSourceId) {
            return message.error('请选择数据源')
          }
          handleAddNode();
        }} className='dark:border-btnDarkBorder'>
          <PlusOutlined />
          {t('w_addNode')}
        </Button>
        <Button
          className='ml-2 relative overflow-hidden'
          onClick={handleAIGenerate}
          style={{
            position: 'relative',
            border: '0px',
          }}
        >
          <div
            style={{
              position: 'absolute',
              inset: 0,
              borderRadius: '5px',
              padding: '1px',
              background: mode === 'light' ? 'linear-gradient(to right, rgb(182, 32, 224), rgb(204, 203, 204))' : 'linear-gradient(to right, rgb(182, 32, 224), rgba(255, 255, 255, 0.94))',
              WebkitMask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
              WebkitMaskComposite: 'xor',
              maskComposite: 'exclude',
            }}
          />
          <WorkbenchesIcon type='agent' />
          <span
            style={{
              background: mode === 'light' ? 'linear-gradient(to right, rgb(182, 32, 224), rgb(204, 203, 204))' : 'linear-gradient(to right, rgb(182, 32, 224), rgba(255, 255, 255, 0.94))',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              position: 'relative',
              zIndex: 1,
            }}
          >
            {t('w_AIGenerated')}
          </span>
        </Button>
        <div className='mx-2 w-1 h-6 border-r-2 border-borderColor dark:border-darkBorderColor'></div>

        <Button className='dark:border-btnDarkBorder'
          disabled={!currentItem?.modelInfo?.id}
          onClick={() => openDetailsmodel('model')}
        >
          <WorkbenchesIcon type='模型' />
        </Button>
        <Button
          className='ml-2 dark:border-btnDarkBorder'
          disabled={!currentItem?.modelInfo?.id}
          onClick={() => openDetailsmodel('log')}
        >
          <WorkbenchesIcon type='日志' />
        </Button>
        <Button
          className='ml-2 dark:border-btnDarkBorder'
          disabled={!currentItem?.modelInfo?.id}
          onClick={() => openDetailsmodel('preview')}
        >
          <WorkbenchesIcon type='查询' />
        </Button>
        <div className='mx-2 w-1 h-6 border-r-2 border-borderColor dark:border-darkBorderColor'></div>

        {
          currentItem?.modelInfo?.id ?
            <Button disabled={!!currentItem?.modelInfo?.status} className='dark:border-btnDarkBorder' onClick={delModel}>
              <DeleteOutlined />
            </Button> : null
        }

        <Button
          className='ml-2 dark:border-btnDarkBorder'
          onClick={() => {
            if (!currentItem?.dataSourceId) {
              return message.error('请选择数据源')
            }
            const data = handleSave();
            if (!data) {
              return;
            }
            const {
              name, nameEng, comment, businessDomainIds, isAccelerationEnabled, scheduleType, executionTime
            } = currentItem?.modelInfo || {}
            const params = {
              name,
              nameEng,
              comment,
              businessDomainIds: businessDomainIds ? businessDomainIds.split(',').filter(Boolean) : [],
              isAccelerationEnabled: !!isAccelerationEnabled ? 1 : 0,
              runTime: [] as any[],
            }
            if (params.isAccelerationEnabled) {
              params.runTime = [Number(scheduleType), executionTime];
            }
            saveCanvasModalUpdataNodeModal(params);
          }}
        >
          <WorkbenchesIcon type='保存' />
          {t('save')}
        </Button>
        <Button
          disabled={!currentItem?.modelInfo?.id}
          className='ml-2 dark:border-btnDarkBorder'
          onClick={() => {
            updateStatusChange(getCurrentItemChange)
          }}
        >
          <WorkbenchesIcon type={currentItem?.modelInfo?.status ? '下线' : '发布'} />
          {t(currentItem?.modelInfo?.status ? 'w_Offline' : 'publish')}
        </Button>
        <Select
          className='w-40 ml-20 dark:border-btnDarkBorder'
          showSearch
          disabled={!!currentItem?.modelInfo?.id}
          value={currentItem?.dataSourceId || ''}
          optionFilterProp="children"
          filterOption={(input, option) =>
            (option?.children?.props?.title ?? '')?.toLowerCase?.().includes(input.toLowerCase())
          }
          onChange={(value) => {
            if (currentItem.dataSourceId) {
              Modal.confirm({
                title: '确认切换数据源',
                content: '切换数据源将清空画布，是否继续？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  setDataSource(value);
                }
              });
              return;
            }
            setDataSource(value);
          }}
        >
          {
            treeData.map((i: any) => {
              return (
                <Select.Option value={i.key}>
                  <div className='flex items-center w-40 ' title={i.name}>
                    <WorkbenchesIcon type='starrocks' />
                    <div className='ml-2'> {i.name}</div>
                  </div>
                </Select.Option>
              )
            })
          }

        </Select>
      </div>

      <div className='w-full mt-2 svg-model' style={{ height: '100%' }}>
        <div ref={container} className='w-full h-full' style={{ height: 600, marginTop: 16 }} />
        {
          loading ?
            <div className="flex items-center justify-center absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-50" >
              <Spin size="large" />
              <p className='text-[#999] italic ml-2'>加载中...</p>
            </div> : null
        }

        {/* 节点连接线 */}
        {open && <EdgeModal
          open={open}
          form={form}
          onCancel={(edge) => {
            if (modalType == 'add') {
              graph.current.removeCell(edge);
            }
            setOpen(false);
          }}
          onOk={(e: any) => {
            const { join } = e.formData || {};
            e.edge.setLabels([
              {
                attrs: {
                  label: {
                    text: join,
                  },
                },
                tools: [
                  {
                    name: 'button-remove',
                    args: { distance: -40 },
                  },
                ],
              },
            ]);
            e.edge.setData({
              ...e.formData,
            });
            setOpen(false);
          }}
          type={modalType} />
        }
      </div>

      <div style={{ width: '100%' }}>
        {openInDetailModel && <InDetailModel open={openInDetailModel} measurementValue={measurementValue} modelType={detailType} currentItem={currentItem} onClose={() => {
          setOpenInDetailModel(false);
        }} />}
      </div>
      {/* 保存画布信息 */}
      {saveCanvasModalOpen && <SaveCanvasModal
        graph={graph}
        currentItem={currentItem}
        checkedState={checkedState}
        open={saveCanvasModalOpen}
        form={saveCanvasModalForm}
        onCancel={() => {
          saveCanvasModalSetOpen(false);
        }}
        onOk={(id) => {
          getCurrentItemChange(id);
          saveCanvasModalSetOpen(false);
        }}
        type={saveCanvasModalModalType} />
      }

      {/* 右键边菜单 */}
      {edgeContextMenu && (
        <div
          style={{
            position: 'fixed',
            left: edgeContextMenu.x,
            top: edgeContextMenu.y,
            zIndex: 9999,
            borderRadius: 6,
            padding: 0,
            minWidth: 120,
          }}
          onClick={e => e.stopPropagation()}
        >
          <Button
            className=' w-full rounded-t-md'
            onClick={() => {
              handleCreate(edgeContextMenu.edge, 'edit');
              closeEdgeContextMenu();
            }}
          >
            编辑
          </Button>
          <Button
            className='w-full rounded-t-md' danger
            style={{ marginTop: '1px' }}
            onClick={() => {
              Modal.confirm({
                title: '确认删除',
                content: '确定删除这条边，是否继续？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  const edge = edgeContextMenu.edge;
                  // console.log('edg32233e',edgeContextMenu, edge)
                  if (graph.current) {
                    
                    graph.current.removeEdge(edge.id);
                    closeEdgeContextMenu();
                  }
                }
              });
            }}
          >
            删除
          </Button>
        </div>
      )}
    </div>


  );
};

export default FlowEditor;